package com.wpf.system.controller;

import cn.hutool.core.convert.Convert;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.common.utils.UploadUtils;
import com.wpf.system.entity.Pictures;
import com.wpf.system.service.PicturesService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/pictures")
public class PicturesController {

    @Value("${system.saveFileUrl}")
    private String saveFileUrl;

    @Value("${server.port}")
    private String port;

    @Resource
    PicturesService picturesService;

    @GetMapping("/{bid}")
    public List<Pictures> getPicturesByBid(@PathVariable("bid") String bid){
        return picturesService.getPicturesByBid(bid);
    }

    @PostMapping("/upload")
    public ResultVO savePictures(@RequestParam("files") MultipartFile[] fileList, @RequestParam("bid") String bid) {
        String serverAddress = saveFileUrl +":"+ port;
        int count = 0;
        //不做非空、大小、格式验证，由前端处理
        for(MultipartFile file : fileList){
            String saveUrl = serverAddress + UploadUtils.uploadPictures(file,bid);
            Pictures pictures = new Pictures();
            pictures.setBid(bid);
            pictures.setUrl(saveUrl);
            if(picturesService.save(pictures)){
                count++;
            }
        }
        if (count==fileList.length){
            return ResultUtils.success("上传照片成功！");
        }else if(count<fileList.length&&count>0){
            return ResultUtils.success("成功上传"+count+"张照片！ "+(fileList.length-count)+"张照片上传失败");
        }else {
            return ResultUtils.error("上传照片失败！");
        }
    }

    @DeleteMapping("/{ids}")
    public void deletePicturesByIds(@PathVariable("ids") String ids){
        List<Long> deleteIds = Convert.toList(Long.class,ids.split(","));
        picturesService.deletePicturesByIds(deleteIds);
    }

    @DeleteMapping("/all/{bids}")
    public void deleteAllFiles(@PathVariable("bids") String bids){
        List<String> deleteIds = Convert.toList(String.class,bids.split(","));
        //删除数据库
        picturesService.deletePicturesByBid(deleteIds);
        //删除本地文件
        for( String bid : deleteIds){
            picturesService.deleteAllFiles(bid);
        }
    }

}
